package com.zmn.oms.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.util.*;

/**
 * 类描述：
 *
 * @author LiangHailong
 * @date 2019/09/24 23:37
 */
public final class RequestUtil {
    private static final Logger logger = LoggerFactory.getLogger(RequestUtil.class);

    /**
     * 获取请求参数
     * @param request
     * @return
     */
    public static String getPostParameter(HttpServletRequest request) {
        try (
            BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"))
        ){
            StringBuilder buffer = new StringBuilder();
            String line = null;
            while((line = reader.readLine()) != null) {
                buffer.append(line);
            }

            return buffer.toString();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 获取请求参数
     * @param request
     * @return
     */
    public static String getPostParms(HttpServletRequest request) {
        String params = null;
        try (
            BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"))
        ){
            StringBuilder buffer = new StringBuilder();
            String line = null;
            while((line = reader.readLine()) != null) {
                buffer.append(line);
            }

            params = buffer.toString();
            params = URLDecoder.decode(params, "UTF-8");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return params;
    }

    /**
     * 获取请求参数
     * @param request
     * @return
     */
    public static Map<String, String> getPostParmsMap(HttpServletRequest request) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        if (parameterMap == null || parameterMap.isEmpty()) {
            return Collections.EMPTY_MAP;
        }

        Map<String, String> resultMap = new HashMap<>(parameterMap.size());
        Iterator<Map.Entry<String, String[]>> iterator = parameterMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String[]> pair = iterator.next();
            resultMap.put(pair.getKey(),
                    Optional.ofNullable(pair.getValue())
                    .filter(arr -> arr.length>0 )
                    .map(arr -> arr[0]) // 不支持多个相同的key传值，只取其中一个
                    .orElse(null)
            );
        }

        return resultMap;
    }

    /**
     * 私有构造器，防止外部实例化
     */
    private RequestUtil() {}
}
